const Koa = require("koa");
const router = require("koa-router")();
const koaBody = require("koa-body");
const koaStatic = require("koa-static");
const viewEjs = require("koa-views");

const fs = require("fs");
const path = require("path");

const app = new Koa();
app.use(koaStatic(path.resolve(__dirname,"./public")));
app.use(viewEjs(path.resolve(__dirname,"./public"),{
  map:{html:"ejs"}
}));

app.use(koaBody({
  multipart:true,//支持文件格式
  formidable:{  
      uploadDir: path.join(__dirname, 'public/uploads'),// 上传目录
      keepExtensions: true,// 保留文件扩展名
    maxSize:200*1024*1024   //设置支持最大上传文件大小（默认最大2M，超过2M会报错）
  }
}));

router.get("/",async (ctx,next)=>{
  await ctx.render("upload",{til:"龙波帝国"});
});
router.post('/upload', ctx => {
  const file = ctx.request.files.file;

  const basename = path.basename(file.path);
  ctx.body = { "url": `${ctx.origin}/uploads/${basename}` }

  //ctx.body = { path: file.path }
});


app.use(router.routes()).use(router.allowedMethods());
app.listen(3007,()=>{
	console.log("server is running on 3007!")
})
